<?php
	
	/*
	*	数据库信息修改控制器
	*	@modifyId		获取到被修改信息的ID
	*	@getDetail		从数据库获取详情
	*	@save			修改文成之后将新数据添加到数据库
	*	@display		display 模板文件
	*	@errorDisplay	当修改之后发现错误时调用
	*/
	
	require_once('BaseCtrl.php');
	
	
	class ModifyCtrl extends CtrlBase {
		
		protected $detail;
		
		protected $modifyId;
		
		protected $errorInfo;
		
		/*
		*	构造函数
		*	@保存需要修改的信息的ID
		*	@实例化smarty
		*/
		public function __construct() {
			
			parent::__construct();
			
			parent::checkSession();
			
			$this->errorInfo['nameTips'] = '';
			
			$this->errorInfo['emailTips'] = '';
			
			$this->errorInfo['tellTips'] = '';
			
			$this->errorInfo['schoolTips'] = '';
			
			$this->modifyId = $_GET['id'];
			
		}
		
		
		/*
		*	根据ID来从数据库获取到详情并保存
		*/
		private function getDetail() {
			
			$detailModel = new DetailModel();
			
			$this->modifyId;
	
			$this->detail = $detailModel->getDetail($_GET['id']);
			
		}
		
		
		/*
		*	检查修改后的信息
		*	只处理必填项
		*/
		public function checkModify() {
			
		
			$ctrl_handle = new ModifyModel($_POST, $_FILES);
				
			$flag = $ctrl_handle->checkInfo();
			
			if($flag === 2) {
				
				$this->errorInfo['nameTips'] = '姓名输入有误，请重新输入';
				
				return false;
				
			} else if($flag === 3) {
				
				$this->errorInfo['emailTips'] = '电子邮件输入有误，请重新输入';
				
				return false;
				
			} else if($flag === 4) {
				
				$this->errorInfo['tellTips'] = '电话号码输入有误，请重新输入';
				
				return false;
				
			} else if($flag === 5) {
				
				$this->errorInfo['schoolTips'] = '学校信息输入有误，请重新输入';
				
				return false;
				
			} else {
				
				return true;
				
			}
		}

		
		/*
		*	调用checkModify函数
		*	通过返回值判断信息是否有误
		*	如果没有错误则调用update函数保存到数据库
		*/
		public function save() {
			
			$tmp = $this->checkModify();
			
			if(!$tmp) {
				
				$this->display();
				
				return false;
				
			}
			
			$modifyModel = new ModifyModel($_POST, $_FILES);
			
			if($modifyModel->update($_POST, $this->modifyId)) {
				
				header("Location:/succeed/display");
				
			}
			
		}
	
	
		/*
		*	在开始修改之前先将详情展示给客户端
		*/
		public function display() {
			
			$this->checkSession();
			
			if(!isset($this->detail)) {
				
				$this->getDetail();
				
			}
		 	
			$this->smarty->assign('birthYear', substr($this->detail['birthday'], 0, 4));
			
			$this->smarty->assign('birthDay', substr($this->detail['birthday'], 5));
			
			if($this->detail['has_annex'] === '1') {
				
				$this->smarty->assign('has_annex', '有效');
				
			} else {
				
				$this->smarty->assign('has_annex', '无效');
				
			}
			
			$this->smarty->assign('errorInfo', $this->errorInfo);
			
			$this->smarty->assign('detail', $this->detail);
			
			$this->smarty->display('modify.tpl');
			
 		}
		
	}
?>